package zheezes.eisp.compute.model;

import java.math.BigDecimal;
import java.util.Calendar;

import org.apache.log4j.Logger;

import zheezes.eisp.data.dao.DataAccessor;
import zheezes.eisp.data.orm.CalcTask;
import zheezes.eisp.data.orm.GroupPo;
import zheezes.eisp.data.orm.Summator;
import zheezes.eisp.data.orm.SummatorDailyUse;
import zheezes.util.DateFormatUtil;


public class CondChecker {
	private static Logger logger = Logger.getLogger(CondChecker.class);
	private DataAccessor dataAccessor;

	public int checkZoneLineLose(int znId, Calendar cal) {
		logger.info(String.format("check zone[%d] line loss", znId));
		Summator sm = dataAccessor.getSummatorByZone(znId);
		SummatorDailyUse smdu = null;
		if(sm != null 
				&& (smdu = dataAccessor.querySummatorDailyUseByMpIdAndDate(sm.getMpId(), cal.getTime())) != null
				&& smdu.getPp() != null) {
			int total = dataAccessor.countResMeterByZone(znId);
			int amount = dataAccessor.countResMeterWithDailyUseByZone(znId, cal.getTime());
			GroupPo group = dataAccessor.getGroupById(znId);
			BigDecimal limit = group.getLimit();
			// check the collect ratio
			if (limit == null || total * limit.floatValue() < amount) {
				CalcTask task = new CalcTask();
				task.setTaskType(CalcTask.TASK_CALC_LOSSY);
				task.setTargetType(CalcTask.TARGET_ZONE);
				task.setTargetId(znId);
				task.setStatus(CalcTask.STATUS_QUEUE);
				task.setSource(CalcTask.SOURCE_AUTO);
				task.setDate(cal.getTime());
				task.setCreateDate(Calendar.getInstance().getTime());
				
				// because use the line lost limit, so should use the replace
				return dataAccessor.replaceCalcTask(task);
			} else {
				logger.info(String.format("%d/%d < %s", amount, total, limit.toString()));
			}
		} else {
			logger.info(sm == null ? 
					String.format("there is no summator in zone[%d]", znId) : 
					String.format("summator[%d] has no daily use at %s", sm.getId(), DateFormatUtil.getDateFmt().format(cal.getTime())));
		}
		return -1;
	}

	public void setDataAccessor(DataAccessor dataAccessor) {
		this.dataAccessor = dataAccessor;
	}
}
